<template>
    <a-card
        :title="title"
        class="card beauty-scroll"
        :style="{ width: width + 'px' }"
    >
        <template #extra>
            <a-button size="small" @click="handleStartUp" v-if="checkable"
                >启动
            </a-button></template
        >
        <a-tree
            :show-line="true"
            :show-icon="true"
            :checkable="checkable"
            :tree-data="treeData"
            :default-expanded-keys="[0]"
            :replace-fields="replaceFields"
            v-model:checkedKeys="checkedKeys"
            @select="onSelect"
        >
            <template #switcherIcon>
                <CarryOutOutlined />
            </template>
        </a-tree>
    </a-card>
</template>

<script lang="ts">
import { CarryOutOutlined } from "@ant-design/icons-vue";
import { SelectEvent } from "ant-design-vue/es/tree/Tree";
import { defineComponent, reactive, ref, toRefs } from "vue";

export default defineComponent({
    name: "Tree",
    components: {
        CarryOutOutlined,
    },
    props: {
        width: {
            type: Number,
            default: 245,
        },
        type: {
            type: Number,
            default: 0,
        },
        title: String,
        treeData: Array,
        checkable: {
            type: Boolean,
            default: false,
        },
    },
    setup(props, { emit }) {
        const checkedKeys = ref<string[]>([]);
        const state = reactive({
            replaceFields: { children: "child", title: "name", key: "id" },
            onSelect(selectedKeys: string[], info: SelectEvent) {
                if (props.type === 1) {
                    emit("selectTree", selectedKeys[0]);
                } else {
                    const text =
                        typeof selectedKeys[0] === "number"
                            ? ""
                            : selectedKeys[0];
                    emit("selectTree", text);
                }
            },
            handleStartUp() {
                emit("handleStartUp", checkedKeys.value);
            },
        });

        return {
            checkedKeys,
            ...toRefs(props),
            ...toRefs(state),
        };
    },
    emits: ["selectTree", "handleStartUp"],
});
</script>

<style lang="less" scoped>
.card {
    margin-right: 10px;
    max-height: 100vh;
    overflow-y: auto;
}
</style>>
